﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace B.S.BasicData.Common
{
    public class JwtTools
    {
        /// <summary>
        /// 签发Token令牌
        /// </summary>
        /// <param name="configuration">配置接口</param>
        /// <param name="Uid">用户唯一标识</param>
        /// <returns></returns>
        public string JwtNewString(IConfiguration configuration,string Uid)
        {
            //生成Jwt 
            //Header，选择签名算法
            var signingAlogorithm=SecurityAlgorithms.HmacSha256;
            //Payload,存放用户信息
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,Uid),
                new Claim(ClaimTypes.Name,"张三"),
                new Claim(ClaimTypes.Email,"zhangsan@exaple.com"),
                new Claim(ClaimTypes.Role,"Admin"),
                new Claim(ClaimTypes.DateOfBirth,"2025-01-01",ClaimValueTypes.Date),
                new Claim("CustomClaimType","CustomValue"),
                new Claim("key","value值"),
            };

            //取出私钥并以utf8编码字节输出
            var secretByte = Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]);
            //使用非对称算法对私钥进行加密
            var signingKey=new SymmetricSecurityKey(secretByte);
            //使用HmacSha256来验证加密后的私钥生成数字签名
            var signingCredentitals=new SigningCredentials(signingKey, signingAlogorithm);
            //生成Token
            var Token = new JwtSecurityToken(

                issuer: configuration["Authentication:Issuer"],    //发布者
                audience: configuration["Authentication:Audience"],//接收者
                claims:claims,                                     //存放的用户信息 
                notBefore:DateTime.UtcNow,                         //发布时间
                expires:DateTime.UtcNow.AddDays(1),                //有效期设置为1天
                signingCredentitals                                //数字签名
                );
            //生成字符串Token
            var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);
            return TokenStr;
        }


    }
}
